package com.xiyue.leaspring.action;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Controller//定义控制器
@RequestMapping("/pages")//访问父路径，与方法中的路径进行组合为完整路径
public class UploadAction {//自定义Action程序类

    @GetMapping("/uploadview")
    public String uploadView() {
        return "/photo/photo_upload";//上传表单
    }

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(String msg, MultipartFile photo) throws IOException {
        Map<String,Object> result = new HashMap<>();//保存结果
        result.put("msg",msg);//保存信息
        if(photo==null||photo.isEmpty()){
            result.put("photo-name","nophoto");//没有文件,保存默认名称
        }else {//现在有上传文件
            String photoName = UUID.randomUUID()+"."+ photo.getContentType()
                    .substring(photo.getContentType().lastIndexOf("/")+1);//创建保存文件名称
            String photoPath = ContextLoader.getCurrentWebApplicationContext().getServletContext()
                    .getRealPath(File.separator+"WEB-INF"+File.separator+"upload"+File.separator)+File.separator+photoName;//保存路径
            result.put("photo-size",photo.getSize());//保存文件上传信息
            result.put("photo-mime",photo.getContentType());//保存文件上传信息
            result.put("photo-name",photoName);//保存文件上传信息
            result.put("photo-path",photoPath);//保存文件上传信息
            File file = new File(photoPath);
            File filePath = new File(file.getParent());
            if(!filePath.exists() && !filePath.isDirectory()){
                filePath.mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            photo.transferTo(file);//进行文件转存
        }
        return  result;//返回文件信息
    }
}
